package com.dwxt.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.zfbpay.ZFBUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class ZFBService {

    public BaseResult pay(Map<String, String> params) throws AlipayApiException {
        AlipayRequest request = buildPayRequest(params);
        //实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型），为了取得预付订单信息
        AlipayClient alipayClient = ZFBUtil.bulidAlipayClient();
        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayResponse response;
        if (request instanceof AlipayTradeAppPayRequest) {
            response = alipayClient.sdkExecute(request);
            return BaseResult.ok(response.getBody());
        } else {
            response = alipayClient.execute(request);
            JSONObject result = JSONObject.parseObject(response.getBody());
            return BaseResult.ok(result);
        }
    }

    private AlipayRequest buildPayRequest(Map<String, String> params) {
        Double price = Double.parseDouble(params.get("price"));
        String notifyUrl = params.get("notifyUrl");
        Integer type = Integer.parseInt(params.get("type"));
        String orderId = params.get("orderId");
        AlipayRequest request;
        if (type == 2) {
            //扫码支付
            request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setSubject("智慧城市");//商品名称
            model.setOutTradeNo(orderId);////商户订单号
            model.setTimeoutExpress("70m");//交易超时时间
            model.setTotalAmount(price.toString());//支付总金额
            //model.setProductCode("QUICK_MSECURITY_PAY");//销售产品码，商家和支付宝签约的产品码,固定值
            request.setBizModel(model);
            request.setNotifyUrl(notifyUrl);//异步回调地址（后台）
        } else {
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            request = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            //业务参数传入,可以传很多，参考API
            //model.setPassbackParams(URLEncoder.encode(request.getBody().toString())); //公用参数（附加数据）
            //model.setBody(body.toString());//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
            model.setSubject("智慧城市");//商品名称
            model.setOutTradeNo(orderId);////商户订单号
            model.setTimeoutExpress("70m");//交易超时时间
            model.setTotalAmount(price.toString());//支付总金额
            model.setProductCode("QUICK_MSECURITY_PAY");//销售产品码，商家和支付宝签约的产品码,固定值
            request.setBizModel(model);
            request.setNotifyUrl(notifyUrl);//异步回调地址（后台）
        }
        return request;
    }

    public BaseResult queryPayResult(String orderId) throws AlipayApiException {
        AlipayClient alipayClient = ZFBUtil.bulidAlipayClient();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderId + "\"" +
                "  }");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            //String out_trade_no = response.getOutTradeNo();// 商户订单号
            String tradeStatus = response.getTradeStatus();
            String total_amount = response.getTotalAmount();
            //order = paymentOrderMapper.selectByPrimaryKey(out_trade_no);
            if ("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)) {
                return BaseResult.ok("SUCCESS");
            }
        }
        return BaseResult.build(StatusCode.ORDER_PURCHASE_FAIL);
    }

    public BaseResult refund(String orderId, Double price) throws AlipayApiException {
        //实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型），为了取得预付订单信息
        AlipayClient alipayClient = ZFBUtil.bulidAlipayClient();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(orderId);////商户订单号
        model.setRefundAmount(price.toString());
        model.setRefundReason("商品退款");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizModel(model);
        //request.setNotifyUrl(account.getNotifyUrl());//异步回调地址（后台）

        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        String body = response.getBody();
        String code = com.alibaba.fastjson.JSONObject.parseObject(body).getJSONObject("alipay_trade_refund_response").getString("code");
        if ("10000".equals(code)) {
            return BaseResult.ok("SUCCESS");
        } else {
            log.info("支付宝code:{}", code);
            return BaseResult.ok("Fail");
        }
    }
}
